<template>
  <div class="user-profile">
    <h2>个人中心</h2>
    
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card class="profile-card">
          <div class="profile-header">
            <div class="avatar-container">
              <el-avatar :size="100" :src="avatarUrl">
                {{ userInfo.realName ? userInfo.realName.substring(0, 1) : userInfo.username.substring(0, 1) }}
              </el-avatar>
            </div>
            <h3>{{ userInfo.realName }}</h3>
            <p class="user-role">{{ formatUserRole }}</p>
          </div>
          
          <div class="profile-info">
            <div class="info-item">
              <span class="label">用户名：</span>
              <span>{{ userInfo.username }}</span>
            </div>
            <div class="info-item">
              <span class="label">邮箱：</span>
              <span>{{ userInfo.email }}</span>
            </div>
            <div class="info-item">
              <span class="label">手机：</span>
              <span>{{ userInfo.phone || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="label">加入时间：</span>
              <span>{{ formatDate(userInfo.joinDate) }}</span>
            </div>
            <div class="info-item">
              <span class="label">状态：</span>
              <el-tag :type="userInfo.status === 'active' ? 'success' : 'danger'">
                {{ userInfo.status === 'active' ? '活跃' : '禁用' }}
              </el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>修改个人信息</span>
            </div>
          </template>
          
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
          >
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="form.realName" maxlength="20"></el-input>
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" type="email"></el-input>
            </el-form-item>
            
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" maxlength="11"></el-input>
            </el-form-item>
            
            <el-form-item label="头像" prop="profilePicture">
              <el-input v-model="form.profilePicture" placeholder="请输入头像URL"></el-input>
              <div class="form-tip">输入头像图片的URL地址</div>
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input 
                v-model="form.newPassword" 
                type="password" 
                show-password
                placeholder="留空表示不修改密码"
              ></el-input>
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                v-model="form.confirmPassword" 
                type="password" 
                show-password
                placeholder="留空表示不修改密码"
              ></el-input>
            </el-form-item>
            
            <el-form-item>
              <el-button 
                type="primary" 
                @click="handleUpdate" 
                :loading="loading"
              >保存修改</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const formRef = ref(null)
const loading = ref(false)

// 用户信息
const userInfo = computed(() => userStore.userInfo)

// 头像URL
const avatarUrl = computed(() => {
  return userInfo.value.profilePicture || ''
})

// 格式化用户角色
const formatUserRole = computed(() => {
  const roleMap = {
    'student': '学生',
    'club_leader': '社团负责人',
    'admin': '学校管理员'
  }
  return roleMap[userInfo.value.role] || userInfo.value.role
})

// 表单数据
const form = reactive({
  realName: '',
  email: '',
  phone: '',
  profilePicture: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单校验规则
const rules = reactive({
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { 
      type: 'email', 
      message: '请输入正确的邮箱地址', 
      trigger: ['blur', 'change'] 
    }
  ],
  phone: [
    { required: false, message: '请输入手机号', trigger: 'blur' },
    { 
      pattern: /^1[3-9]\d{9}$/, 
      message: '请输入正确的手机号码', 
      trigger: ['blur', 'change'] 
    }
  ],
  newPassword: [
    {
      validator: (rule, value, callback) => {
        if (value && value.length < 6) {
          callback(new Error('密码长度不能少于6位'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      validator: (rule, value, callback) => {
        if (form.newPassword && !value) {
          callback(new Error('请再次输入新密码'))
        } else if (form.newPassword && value !== form.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})


// 初始化表单数据
const initFormData = () => {
  form.realName = userInfo.value.realName || ''
  form.email = userInfo.value.email || ''
  form.phone = userInfo.value.phone || ''
  form.profilePicture = userInfo.value.profilePicture || ''
  form.newPassword = ''
  form.confirmPassword = ''
}

// 更新用户信息
const handleUpdate = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    loading.value = true
    
    // 构建要更新的数据
    const updateData = {
      realName: form.realName,
      email: form.email,
      phone: form.phone,
      profilePicture: form.profilePicture
    }
    
    // 如果输入了新密码
    if (form.newPassword) {
      updateData.password = form.newPassword
    }
    
    // 调用Store的更新方法
    const res = await userStore.updateUserInfo(updateData)
    
    if (res.code === 200) {
      ElMessage.success('个人信息更新成功')
      // 重置密码字段
      form.newPassword = ''
      form.confirmPassword = ''
    } else {
      ElMessage.error(res.message || '更新失败')
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ElMessage.error('更新失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 初始化
onMounted(() => {
  initFormData()
})
</script>

<style scoped>
.user-profile {
  padding: 20px;
}

.profile-card {
  height: 100%;
}

.profile-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.avatar-container {
  margin-bottom: 15px;
}

.profile-header h3 {
  margin: 10px 0 5px;
  font-size: 18px;
}

.user-role {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.profile-info {
  margin-top: 20px;
}

.info-item {
  margin-bottom: 12px;
  display: flex;
}

.info-item .label {
  width: 80px;
  color: #909399;
}

.card-header {
  font-weight: bold;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>